import React, { useState, useEffect } from 'react';
import {
  Button,
  Layout,
  Card,
  Divider,
  Table,
  Badge,
  message,
  Popconfirm,
  Modal,
  Progress,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import CommentSearch from './components/CommentSearch';
import { RedoOutlined, PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getPageDel } from '@/api/page';
import { useKey } from '@/hooks/index';
import Footers from '@/components/Footer';
import { connect } from 'umi'
import { changePage } from '@/api/page'
function IndexPage(props: any) {
  const { Header, Footer, Content } = Layout;
  //分页功能
  const [pageInfo, setPage] = useState({ page: 1, pageSize: 12 })
  const { setPages, total, dispatch } = props;
  // 获取所有数据
  useEffect(() => {
    dispatch({
      type: 'page/INIT',
      pageInfo,
    })
  }, []);
  //解决key报错
  setPages ? useKey(setPages) : null;
  const Refresh = () => {
    dispatch({
      type: 'page/INIT',
      pageInfo,
    })
  };
  //分页
  const onchanges = (page: number, pageSize: number) => {
    dispatch({
      type: 'page/INIT',
      pageInfo: {
        page,
        pageSize,
      },
    })
  }
  //修改页面管理状态
  const pubils = (id: any, status: any) => {
    if (status === 'publish') {
      status = 'draft'
    } else if (status === 'draft') {
      status = 'publish'
    }
    // console.log(item);
    changePage(id, status)
    dispatch({
      type: 'page/INIT',
      pageInfo,
    })
  }
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 150,
    },
    {
      title: '路径',
      dataIndex: 'path',
      width: 150,
    },
    {
      title: '顺序',
      dataIndex: 'order',
    },
    {
      title: '阅读量',
      dataIndex: 'views',
      render: (col: any) => {
        return (
          <p
            style={{
              width: '20px',
              height: '20px',
              borderRadius: '50%',
              background: 'rgb(82, 196, 26)',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            {col}
          </p>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (col: string) => {
        return col === 'publish' ? (
          <span>
            <Badge status="success" /> 已发布
          </span>
        ) : (
          <span>
            {' '}
            <Badge status="warning" /> 草稿
          </span>
        );
      },
    },
    {
      title: '发布时间',
      dataIndex: 'publishAt',
      render: (col: any) => {
        return new Date(col).toLocaleString(); //时间转换
      },
    },
    {
      title: '操作',
      width: 320,
      // dataIndex: 'status',
      render: (item: any) => (
        <div>
          <a>编辑</a> <Divider type="vertical" />
          <a onClick={() => pubils(item.id, item.status)}>{
            item.status === 'publish' ? '下线' : '发布'
          }</a>
          {/* {
            item.status ==='publish'?<a>下线</a>:<a>发布</a>
          } */}
          <Divider type="vertical" />
          <a onClick={showModal}>查看访问</a> <Divider type="vertical" />{' '}
          <Popconfirm
            title="确认删除这个文章？"
            onConfirm={() => confirm(item)}
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      ),
    },
  ];
  //删除确认按钮
  const confirm = (item: any) => {
    getPageDel(item.id).then((res: any) => {
      if (res.statusCode == 200) {
        dispatch({
          type: 'page/INIT',
          pageInfo,
        })
        message.success('删除成功');
      }
    });
  };
  //取消删除
  const cancel = (e: any) => {
    // console.log(e);
  };
  //多选显示按钮
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;
  const alldel = (arr: any) => {
    arr.forEach((item: any) => {
      getPageDel(item).then((res: any) => {
        if (res.statusCode === 200) {
          dispatch({
            type: 'page/INIT',
            pageInfo,
          });
          message.success('删除成功');
        }
      })
    })
  }
  return (
    <div>
      <Layout>
        <PageHeaderWrapper />
        <Header
          style={{
            background: '#f0f2f5',
            height: '220px',
            padding: '20px 20px 0px 20px',
          }}
        >
          <Card bodyStyle={{ padding: '0px' }}>
            <CommentSearch></CommentSearch>
          </Card>
        </Header>
        <Content style={{ padding: '0px 20px 20px 20px' }}>
          <Card
            title={
              <span style={{ marginLeft: 8 }}>
                {hasSelected ? (
                  <div style={{ height: '20px', width: '300px' }}>
                    <Button style={{ marginLeft: '10px' }}>发布</Button>
                    <Button style={{ marginLeft: '10px' }}>下线</Button>
                    <Button danger style={{ marginLeft: '10px' }} onClick={() => alldel(selectedRowKeys)}>
                      删除
                    </Button>
                  </div>
                ) : (
                  <div style={{ height: '20px' }}></div>
                )}
              </span>
            }
            extra={
              <p>
                <Button type="primary" style={{ marginLeft: '10px' }}>
                  <PlusOutlined />
                  新建
                </Button>
                <RedoOutlined
                  style={{
                    cursor: 'pointer',
                    marginLeft: '20px',
                    fontSize: '20px',
                  }}
                  onClick={() => Refresh()}
                />
              </p>
            }
          >
            <Table
              pagination={{
                // 总数量
                total,
                // 默认的每条页数
                defaultPageSize: 12,
                // 指定每页可以显示多少条
                pageSizeOptions: [8, 12, 24, 36],
                // 用于显示数据总量和当前数据顺序
                showTotal: (total) => {
                  return <>共{total}条</>
                },
                onChange: onchanges,
                // 是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
                showSizeChanger: true
              }}
              rowSelection={rowSelection}
              columns={columns}
              dataSource={setPages}
            />
          </Card>
        </Content>
        <Footer>
          <Footers></Footers>
        </Footer>
        <Modal title="访问统计"
          open={isModalOpen}
          footer={null}
          onOk={handleOk}
          onCancel={handleCancel}>
          <Progress percent={30} />
          <Progress percent={15} />
          <Progress percent={80} />
          <Progress percent={60} />
          <Progress percent={50} />
          <Progress percent={10} />
        </Modal>
      </Layout>
    </div>
  );
}
// connect接收两个参数
// 1. 函数 mapStateToProps
const mapStateToProps = (state: any) => {
  const { page } = state
  return page
}
export default connect(mapStateToProps)(IndexPage)
